<?php
/**
 * @version $Id: wikiinclude.php 22 2009-03-27 07:44:54Z der.el.kuku $
 * @package    WikiInclude
 * @subpackage
 * @author     EasyJoomla {@link http://www.easy-joomla.org Easy-Joomla.org}
 * @author     Nikolai Plath {@link http://www.easy-joomla.org}
 * @author     Created on 07-Mar-2009
 */

//--No direct access
defined( '_JEXEC' ) or die( '=;)' );

$mainframe->registerEvent( 'onBeforeDisplayContent', 'wikiinclude' );

/**
 * This plugin will trigger the string {WikiInclude}
 *
 * @param $row
 * @param $params
 * @param $page
 *
 * @return void
 */
function wikiinclude( &$row, &$params, $page=0 )
{
	if( strpos($row->text, '{WikiInclude') === false )
	{
		//--The tag is not found in content - abort..
		return;
	}
	 
	$DEBUG = true;
#	$DEBUG = false;

	$regex = '/{WikiInclude\s*.*?}/i';
	$stdURL = 'http://wiki.joomla-nafu.de/jn/';
	$replacement = '';

	//--Search for this tag in the content
	#  $regex = '/{WikiInclude\s(.*?)}/i';
	preg_match_all( $regex, $row->text, $matches );

	$load = str_replace( 'WikiInclude', '', $matches[0][0] );
	$load = str_replace( '|', '', $load );
	$load = str_replace( '{', '', $load );
	$load = str_replace( '}', '', $load );
	$load = trim( $load );
	

	$db = JFactory::getDBO();
	$query = ' SELECT * FROM #__wikiinclude '.
					'  WHERE title = '.$db->quote($load);
			$db->setQuery( $query );
			$data = $db->loadObject();
			if( ! $data || ! isset($data->text))
			{
				$replacement = 'Invalid page';
			}
			else
			{
				$replacement = $data->text;
			}
	//--Replace tag in content
	$row->text = preg_replace( $regex, $replacement, $row->text );
			
#	print_r($data);

	return;
		
	
	
	$url = $stdURL.$load;

	$replacement .=( $DEBUG ) ? '<div style="border: 2px dashed red; margin-top: 1em;">' : '';
	$replacement .=( $DEBUG ) ? '<h2>Including &rArr; <a href="'.$url.'">'.$url.'</a> &bull; <a href="'.$url.'?action=render">?action=render</a></h2>' : '';
	$replacement .=( $DEBUG ) ? '<h2 style="color: red; border-bottom: 2px dashed red;">WikiInclude START</h2>' : '';
	$result = get_web_page( $url.'?action=render' );

	if ( $result['errno'] != 0 )
	{
		$replacement .= 'error: bad url, timeout, redirect loop ... '.$result['errno'];
	}
	else if ( $result['http_code'] != 200 )
	{
		$replacement .= 'error: no page, no permissions, no service ... '.$result['http_code'];
	}
	else
	{
		/**** work here... ****/
		$cleaned = $result['content'];
		$cleaned = str_replace('http://wiki.joomla-nafu.de/index.php?title=', 'index.php?option=com_content&task=findkey&tmpl=component&keyref=', $cleaned);
		$cleaned = str_replace('http://wiki.joomla-nafu.de/jn/', 'index.php?option=com_content&task=findkey&tmpl=component&keyref=', $cleaned);
		
		$cleaned = str_replace('&action=edit&redlink=1', '', $cleaned);
#http://wiki.joomla-nafu.de/index.php?title=Screen.content.15&action=edit&redlink=1
#http://xhelp.der-beta-server.de/index.php?option=com_content&task=findkey&tmpl=component&keyref=screen.cpanel.15
#http://test.nik/j_159_de/index.php?option=com_content&task=findkey&tmpl=component&keyref=Screen.content.15&action=edit&redlink=1&Itemid=54
#http://wiki.joomla-nafu.de/jn/Screen.users.15

		$replacement .= $cleaned;
	}

	$replacement .=( $DEBUG ) ? '<h2 style="color: red; border-top: 2px dashed red;">WikiInclude END</h2>' : '';
	$replacement .=( $DEBUG ) ? '</div>' : '';

	//--Replace tag in content
	$row->text = preg_replace( $regex, $replacement, $row->text );

	return;
}//function

/**
 * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
 * array containing the HTTP server response header fields and content.
 */
function get_web_page( $url )
{
	$options = array(
	CURLOPT_RETURNTRANSFER => true,     // return web page
	CURLOPT_HEADER         => false,    // don't return headers
#	CURLOPT_FOLLOWLOCATION => true,     // follow redirects
	CURLOPT_ENCODING       => "",       // handle all encodings
	CURLOPT_USERAGENT      => "kukuspider", // who am i
	CURLOPT_AUTOREFERER    => true,     // set referer on redirect
	CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
	CURLOPT_TIMEOUT        => 120,      // timeout on response
	CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
	);

	$ch      = curl_init( $url );
	curl_setopt_array( $ch, $options );
	$content = curl_exec( $ch );
	$err     = curl_errno( $ch );
	$errmsg  = curl_error( $ch );
	$header  = curl_getinfo( $ch );
	curl_close( $ch );

	$header['errno']   = $err;
	$header['errmsg']  = $errmsg;
	$header['content'] = $content;
	return $header;
}